package com.tengju.bff.interfaces.shared.servlet;

import org.apache.shiro.web.filter.authc.AnonymousFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class AnonFilter extends AnonymousFilter {

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        httpResponse.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader("Origin"));
        httpResponse.setHeader("Access-Control-Allow-Methods", httpRequest.getMethod());
        httpResponse.setHeader("Access-Control-Allow-Headers", httpRequest.getHeader("Access-Control-Request-Headers"));
        if (httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpResponse.setStatus(HttpStatus.OK.value());
            return false;
        }

        HttpServletRequest req = (HttpServletRequest) request;
        UserServletContext userServletContext = new UserServletContext();
        userServletContext.setIp(request.getRemoteAddr());
        userServletContext.setVersion(req.getHeader("tj_version"));
        userServletContext.setFrom(!StringUtils.isEmpty(req.getHeader("tj_from")) ? req.getHeader("tj_from") : req.getHeader("from"));
        userServletContext.setPlatform(req.getHeader("tj_platform"));
        userServletContext.setDevice(req.getHeader("tj_device"));
        userServletContext.setWeexVersion(req.getHeader("tj_weex_version"));
        userServletContext.setRequest((HttpServletRequest) request);
        userServletContext.setResponse((HttpServletResponse) response);
        //获取请求url
        String reqPath = WebUtils.getPathWithinApplication(WebUtils.toHttp(request));
        userServletContext.setRequestPath(reqPath);
        //技术人员请求test接口 需传密钥
        Map<String, Object> param = new HashMap<>();
        param.put("test_secret_key", Optional.ofNullable(req.getHeader("test")).orElse(""));
        userServletContext.setParamMap(param);

        ServletContextUtil.setServletContext(userServletContext);
        return super.preHandle(request, response);
    }
}
